#

| Chapter 47 C Shell Programming...NOT |

## 47.5 Using C Shell Arrays

The C shell can treat its shell variables as word lists. They're a lot like arrays (52.9) in other programming languages, so that's what I'll call them. The C shell's path (6.5), cdpath (14.5), and mail (21.8) shell variables are arrays, for example. By the way, arrays are great for storing information in your shell setup files (2.2).

To set an array, use parentheses around the value. Put a space between array members. Inside the parentheses, you can use single quotes, backquotes, double quotes, and so on. Here's how to put fix the report in the first member of the job array and resign as the second member:

>     % set job=("Fix the report" resign)

A dollar sign (`$`) before the name of a shell variable gives you its value. That gives all members of an array, too, because the array is stored as a shell variable. To pick out a particular member, put its number in square brackets after the name. For example:

>     % echo $job
>     Fix the report resign
>     % echo $job[1]
>     Fix the report

Like the Bourne shell shift (44.17) command, the C shell shift command shifts the command-line arguments. It also shifts array members. Let's shift the job array:

>     % shift job
>     % echo $job[1]
>     resign

Tom Christiansen told me that putting your directory stack (14.6) in an array is really useful. He's right. You might add an alias (10.2) for pushd and popd that stores the dirs output into an array named dirs:

>     alias pushd 'pushd \!* && set dirs=(`dirs`)'
>     alias popd 'popd \!* && set dirs=(`dirs`)'

Then, to look in the third directory in your stack, use a command like `ls $dirs[3]`. Or, use an array with a foreach loop (9.11) to step through the members one-by-one. For instance, you might need to find the file frobozz that you put in some directory in your stack. Use the -e test (47.4) to look for a file that exists:

    ?
    % foreach dir ($dirs)
    ? if (-e $dir/frobozz) echo "frobozz is in $dir"
    ? end
    frobozz is in /work/vol3/ch02.files/summaries
    %

- JP

47.4 C Shell Variable Operators and Expressions |  | 47.6 Quick Reference: C Shell switch Statement